package com.geovis.emergency.spd.controller.mobile;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.geovis.common.auth.util.AuthUtil;
import com.geovis.common.core.api.Result;
import com.geovis.common.core.controller.BaseController;
import com.geovis.emergency.spd.biz.pc.service.IPcDrillDisasterEventService;
import com.geovis.emergency.spd.biz.system.service.ISystemDeptService;
import com.geovis.emergency.spd.biz.system.service.ISystemDictService;
import com.geovis.emergency.spd.cache.UserCache;
import com.geovis.emergency.spd.entity.mobile.pojo.vo.PcDrillDisasterEventMobileListVO;
import com.geovis.emergency.spd.entity.pc.entity.PcDrillDisasterEvent;
import com.geovis.emergency.spd.entity.pc.pojo.constant.PcDisasterConstant;
import com.geovis.emergency.spd.entity.pc.pojo.constant.PcMessageConstant;
import com.geovis.emergency.spd.entity.pc.pojo.dto.PcDrillDisasterEventDTO;
import com.geovis.emergency.spd.entity.pc.pojo.enums.DisasterEventStatusEnum;
import com.geovis.emergency.spd.entity.pc.pojo.enums.ResponseTypeEnum;
import com.geovis.emergency.spd.entity.pc.pojo.enums.SourceTypeEnum;
import com.geovis.emergency.spd.entity.system.entity.SystemDept;
import com.geovis.emergency.spd.util.MsgUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：linwl
 * @date ：Created in 2022/6/23 9:33
 * @description：移动端-演练灾害事件相关接口
 * @version: v1
 */
@RestController
@RequestMapping("/mobile/pcCheckIn")
@RequiredArgsConstructor
@Api(value = "移动端-应急预案指挥模块-演练灾害事件相关接口", tags = "移动端-应急预案指挥模块-演练灾害事件相关接口")
@Slf4j
public class PcDrillDisasterEventMobileController extends BaseController<IPcDrillDisasterEventService> {

    private final ISystemDictService systemDictService;
    private final ISystemDeptService systemDeptService;

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "事件列表", notes = "传演练id")
    @PostMapping("/getList/{drillId}")
    public Result<List<PcDrillDisasterEventMobileListVO>> getList(@PathVariable("drillId") String drillId) {
        String userId = AuthUtil.getCurrentUserId();
        LambdaQueryWrapper<PcDrillDisasterEvent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PcDrillDisasterEvent::getPcDrillId,drillId);
        wrapper.eq(PcDrillDisasterEvent::getCreateBy,AuthUtil.getCurrentUsername());
        wrapper.orderByDesc(PcDrillDisasterEvent::getCreateTime);
        List<PcDrillDisasterEvent> list = baseService.list(wrapper);

        List<PcDrillDisasterEventMobileListVO> voList = list.stream().map(e->{
            PcDrillDisasterEventMobileListVO vo = new PcDrillDisasterEventMobileListVO();
            vo.setId(e.getId());
            vo.setTitle(e.getTitle());
            vo.setContent(e.getContent());
            vo.setEventType(systemDictService.getValue(e.getType(),PcDisasterConstant.DISASTER_TYPE));
            vo.setEventLevel(systemDictService.getValue(e.getLevel(),PcDisasterConstant.EVENT_LEVEL));
            vo.setEventLevelCode(e.getLevel());
            vo.setEventTypeCode(e.getType());
            vo.setAddress(e.getAddress());
            LocalDate submitTimeDate=e.getSubmitTime().toLocalDate();
            vo.setTime(LocalDateTimeUtil.format(e.getSubmitTime(),"yyyy-MM-dd HH:mm:ss"));
            vo.setTimeTag(submitTimeDate.toString());
            return vo;
        }).collect(Collectors.toList());

//        String tempTime = "";
//        for (PcDrillDisasterEventMobileListVO vo : voList) {
//            if(StrUtil.isNotBlank(vo.getTimeTag()) && tempTime.equals(vo.getTimeTag())){
//                vo.setTimeTag("");
//            }else{
//                tempTime = vo.getTimeTag();
//            }
//        }
        return Result.ok(voList);
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "事件上报", notes = "事件上报")
    @PostMapping("/reportEvent")
    public Result reportEvent(@Validated @RequestBody PcDrillDisasterEventDTO pcDisasterEvent) {
        pcDisasterEvent.setSourceType(SourceTypeEnum.NEW_EVENT.getCode());
        pcDisasterEvent.setResponseType(ResponseTypeEnum.BROADCAST_EVENT.getCode());
        if(AuthUtil.getCurrUser().getDeptId()!=null) {
            SystemDept dept = systemDeptService.getById(AuthUtil.getCurrUser().getDeptId());
            if(dept!=null){
                pcDisasterEvent.setSource(dept.getDeptName());
            }else{
                pcDisasterEvent.setSource(AuthUtil.getCurrentUsername());
            }
        }else{
            pcDisasterEvent.setSource(AuthUtil.getCurrentUsername());
        }
        PcDrillDisasterEvent pcDrillDisasterEvent=baseService.reportEvent(pcDisasterEvent,null,true);
        if(pcDrillDisasterEvent!=null && pcDrillDisasterEvent.getId()!=null)
        {
            MsgUtil.pushMsgByDrillUser(PcMessageConstant.TYPE_REPORT_EVENT,pcDrillDisasterEvent.getTitle(),pcDrillDisasterEvent.getContent(),pcDrillDisasterEvent.getPcDrillId(),pcDrillDisasterEvent.getId());
        }
        return Result.ok();
    }
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "已下发的响应行动事件",notes = "传演练id")
    @GetMapping("/eventList/{drillId}")
    public Result<List<PcDrillDisasterEvent>> eventList(@PathVariable String drillId){
        List<PcDrillDisasterEvent> list = baseService.list(
                Wrappers.lambdaQuery(PcDrillDisasterEvent.class)
                        .eq(PcDrillDisasterEvent::getResponseType,ResponseTypeEnum.RESPONSE_MSG.getCode())
                        .eq(PcDrillDisasterEvent::getPcDrillId, drillId)
                        .and(ew -> ew.eq(PcDrillDisasterEvent::getStatus, DisasterEventStatusEnum.IN_PROGRESS.getCode()).or()
                                .eq(PcDrillDisasterEvent::getStatus, DisasterEventStatusEnum.COMPLETED.getCode())
                        )
                        .orderByDesc(PcDrillDisasterEvent::getSubmitTime)
        );
        return Result.ok(list);
    }
}
